<?php

namespace Admin\Model\DAO;

use Zend\Db\TableGateway\AbstractTableGateway;
use Admin\Entity\SerialBook;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Adapter\Adapter;

class CiculationTable extends AbstractTableGateway {

    protected $table;
    protected $adapter;
    protected $resultSetPrototype;

    public function __construct(Adapter $adapter) {
        $this->table = 'lib_ciculations';
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
    }

    public function getListBookBorrow($cardBarcode) {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from(array('cl' => $this->table))
                ->join(array('rd' => 'lib_readers'), 'rd.cardBarcode = cl.cardBarcode', array())
                ->join(array('sb' => 'lib_serialBooks'), 'sb.bookID = cl.bookID', array('bookStatus', 'serial'))
                ->join(array('bs' => 'lib_bookStores'), 'bs.bookBarcode = sb.bookBarcode');
        $where = new Where();
        $where->equalTo('cl.cardBarcode', $cardBarcode);
        $select->where($where);
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        $resultSet->buffer();
        $resultSet->next();
        return $resultSet;
    }

    public function fetchAll() {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->columns(array('dateBorrow', 'librarianName'))
                ->from(array('cl' => $this->table))
                ->join(array('sb' => 'lib_serialBooks'), 'sb.bookID = cl.bookID', array('bookBarcode', 'serial'))
                ->join(array('bs' => 'lib_bookStores'), 'bs.bookBarcode = sb.bookBarcode')
                ->join(array('rd' => 'lib_readers'), 'rd.cardBarcode = cl.cardBarcode', array('cardBarcode'))
                ->join(array('us' => 'lib_users'), 'us.userID = rd.userID', array('fullName'))
                ->join(array('c' => 'tbl_class'), 'c.classID = rd.classID', array('className'))
                ->join(array('f' => 'tbl_faculties'), 'f.facultyID = c.facultyID', array('facultyName'));
        $select->order(array('sb.bookBarcode','sb.serial'));
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        $resultSet->buffer();
        $resultSet->next();
        return $resultSet;
    }

    public function deleteRow($bookID) {
        $this->delete(array('bookID' => $bookID));
    }

    public function saveData($data) {
        $this->insert($data);
    }
    public function updateRow($bookID,$data) {
        $this->update($data, array('bookID' => $bookID));
    }

}

